"""
Author : Mr.Sun
DateTime : 2022/10/10.14:38
FileName : EmailUtil.py
Desc :  发送邮件相关
查询当天的更新职位 发送邮件
"""

import os
import json
import time
import datetime
import smtplib
from jinja2 import Environment, FileSystemLoader
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from core.OperateSqlite import sqliteOperate
from utils.logger import logger

project_dir = os.path.dirname(os.path.dirname(__file__))
template_path = os.path.join(project_dir, 'template')

today = datetime.date.today()

person_dream = {
    "ssc": {
        "email": ["1248185022@qq.com"],
        "key_words": ("安徽", "合肥", "阜阳", "北京", "天津", "青岛", "威海", "南京", "无锡",
                      "苏州", "伊春", "哈尔滨", "黄山", "新疆", "阿克苏", "喀什", "黑龙江", "伊春")
    },
    "wbn": {
        "email": ["1105784640@qq.com"],
        "key_words": ("北京", "天津", "青岛", "黑龙江", "伊春", "哈尔滨", "沈阳")
    },
    "lcj": {
        "email": ["1367546524@qq.com"],
        "key_words": ("北京", "天津", "湖南")
    }
}


# 填充页面参数
def generate_position_by_day(day, position_message, result_path):
    try:
        env = Environment(loader=FileSystemLoader(template_path))
        template = env.get_template('position.html')
        with open(result_path, 'w+') as fout:
            html_content = template.render(day=day, body=position_message)
            fout.write(html_content)
    except Exception as e:
        logger.error("生成页面失败" + str(e))


# 生成页面
def get_position_from_database(sql_result, file_path):
    try:
        # 处理查询结果
        result = []
        for i in sql_result:
            result.append({"type": i[0], "url": i[1], "title": i[2]})
        logger.info("generate page information is " +
                    json.dumps(result, ensure_ascii=False))
        # 生成页面
        generate_position_by_day(str(today), result, file_path)
        logger.info(" page generated successfully .")
    except Exception as e:
        logger.error("generated page error is " + str(e))


# 发送邮件
def send_email(file_path, receiver_list, name):
    try:
        with open(file_path, 'r') as content:
            detail = content.read()
        receivers = receiver_list
        cc_receivers = []

        sender = "shicheng_sun@qingsongchou.com"
        mail_pass = 'Ssc@950118'

        msg = MIMEMultipart('related')
        # 发件人
        msg["From"] = sender
        # 收件人
        msg["To"] = ";".join(receivers)

        mail_subject = "【" + str(today) + "】职位更新"
        msg["Subject"] = mail_subject
        msg.attach(MIMEText(str(detail), 'html', 'utf-8'))

        # 不管是发送还是抄送都需要抄送都需要添加到发送列表
        receiver = receivers + cc_receivers

        try:
            # 启动SMTP服务，端口465
            smtpObj = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465)
            smtpObj.login(sender, mail_pass)
            smtpObj.sendmail(sender, receiver, msg.as_string())
            smtpObj.quit()
            # 增加发送记录
            send_record_sql = "insert into email_record(receiver,send_date,content) values(?,?,?) "
            sqliteOperate().insert_data(
                send_record_sql,
                data=(name + ' _ ' + str(receiver_list[0]), today, detail))
            logger.info("email record and  send success。")
        except smtplib.SMTPException as e:
            logger.error('smtplib error is ' + str(e))
    except Exception as e:
        logger.error("send_email error is " + str(e))


def do_work():
    try:
        for key, values in person_dream.items():
            name_file = 'template/' + key + '_result.html'
            result_path = os.path.join(project_dir, name_file)
            sql = "select exam_type,url,title from job_information where create_time>'" + str(
                today) + "' and key_word in (%s) ;" % ",".join(
                ['?'] * len(values['key_words']))
            sql_result = sqliteOperate().search_data_email(
                sql, values['key_words'])
            get_position_from_database(sql_result, result_path)
            logger.info(key + "'s email is generate success waiting send.")
            send_email(result_path, values['email'], key)
            time.sleep(15)
    except Exception as e:
        logger.error("do_work email error is " + str(e))


if __name__ == '__main__':
    do_work()
